const qiniu = require('qiniu');
const path = require('path');

const { accessKey, secretKey, bucket } = require('../../config/config.qiniu');

class UploadService {
  async upload(file) {
    const { filename, filepath } = file;

    const extname = path.extname(filename);
    const key = `${Date.now()}${extname}`;

    const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
    const options = {
      scope: bucket,
    };
    const putPolicy = new qiniu.rs.PutPolicy(options);

    const uploadToken = putPolicy.uploadToken(mac);

    const config = new qiniu.conf.Config();

    const formUploader = new qiniu.form_up.FormUploader(config);

    const putExtra = new qiniu.form_up.PutExtra();

    const result = await new Promise((resolve, reject) => {
      formUploader.putFile(uploadToken, key, filepath, putExtra, function(respErr, respBody) {
        if (respErr) {
          reject(respErr);
        }
        resolve(respBody);
      });
    });

    return result;
  }
}

module.exports = UploadService;
